package com.home.cca.network;

import android.util.Log;

import com.google.gson.Gson;
import com.home.cca.model.Order;

import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.stream.Collectors;

import okhttp3.Request;

public class QueryOrderDetailRequest {

    private static final String URL = ApiClient.getBaseUrl() + "/SupplierManager/PSOrderMgr/PSOrderDetail?buyOrderId=%s&_=1734248988823";

    public static List<Order.Material> query(int orderId) throws IOException {
        // 构建请求
        Request request = new Request.Builder()
                .url(String.format(Locale.getDefault(), URL, orderId))
                .get()
                .addHeader("Accept", "application/json, text/javascript, */*; q=0.01")
                .addHeader("Accept-Language", "zh-CN,zh;q=0.9")
                .addHeader("Connection", "keep-alive")
                .addHeader("Cookie", ApiClient.getCookie())
                .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36")
                .addHeader("X-Requested-With", "XMLHttpRequest")
                .build();

        try {
            String execute = ApiClient.execute(request);
            String[] split = execute.split("\n");
            for (String str : split) {
                String trim = str.trim();
                if (trim.startsWith("var model") && trim.endsWith(";")) {
                    String o = trim.substring(11, trim.length() - 1);
                    Order order = new Gson().fromJson(o, Order.class);
                    return order.getMatList()
                            .stream()
                            .filter(it -> it.getMatName() != null && !Objects.equals(it.getMatName().trim(), ""))
                            .collect(Collectors.toList());
                }
            }
        } catch (Exception e) {
            Log.e(QueryOrderDetailRequest.class.getSimpleName(), "query: ", e);
        }
        return Collections.emptyList();
    }

}